﻿using System.Windows;
using System.Windows.Controls;
using AduSkin.Controls.Metro;
using CommunityToolkit.Mvvm.Messaging;
using Microsoft.Extensions.DependencyInjection;
using Model.Tokens;
using Template.net.Core.userControl;
using Utils.NLogHelper;
using ViewModel;

namespace Template.net.Core
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            #region 检测实例

            var mName = System.Diagnostics.Process.GetCurrentProcess().MainModule!.ModuleName;
            var pName = System.IO.Path.GetFileNameWithoutExtension(mName);
            var myProcess = System.Diagnostics.Process.GetProcessesByName(pName);
            if (myProcess.Length > 1)
            {
                MessageBox.Show("本程序一次只能运行一个实例！");
                Application.Current.Shutdown();
                return;
            }

            #endregion
            
            var splashScreen = new SplashScreen("Resources/background02.jpg");
            splashScreen.Show(true);
            
            var start = new StartUp();
            var services = start.Starter();
            Deploy.ConfigureServices(services);
            Deploy.ServiceProvider = services.BuildServiceProvider();
            StartUp.LogHelper = Deploy.ServiceProvider!.GetRequiredService<INlogHelper>();
            WeakReferenceMessenger.Default.Send(Deploy.ServiceProvider); 
            WeakReferenceMessenger.Default.Register<MainContentTokenModel>(this,GetUserControl);
            base.OnStartup(e);
            //初始化通知弹框
            NoticeManager.Initialize();
            WeakReferenceMessenger.Default.Send(new MainContentTokenModel() { Token = "Main" });
        }

        private void GetUserControl(object recipient, MainContentTokenModel message)
        {
            switch (message.Token)
            {
                case "Login":
                    WeakReferenceMessenger.Default.Send<UserControl>(new LoginControl());
                    break;
                case "Main":
                    WeakReferenceMessenger.Default.Send<UserControl>(new MainControl());
                    break;
            }
        }

        protected override void OnExit(ExitEventArgs e)
        {
            NoticeManager.ExitNotifiaction();
            base.OnExit(e);
        }
    }
}